<?php
namespace Home\Controller;
use Think\Controller;
use Org\Util\Wechat;

class WxController extends Controller {

	private $WX = null;
	private $conf = array('appid' => 'wxac5800b79941b855', 'appsecret' => '1fb89ac1bb74743210dac561a31a564e', );

	public function _initialize() {
		$this -> WX = new Wechat($this -> conf);
	}

	public function index() {
		$this -> show();
	}

	public function pay() {
		$this -> assign('openid', session('openid'));
		$this -> display();
	}

	public function getPayParm() {
		$order_id = date('Ymd_His') . '_' . mt_rand(1000, 9999);
		$NotifyUrl = 'http://www.xxx.com/Home/Index/paynotice';
		$conf = array('body' => '支付demo', 'attach' => 'test', 'out_trade_no' => $order_id . '_' . mt_rand(900, 9000), 'total_fee' => 1000, 'goods_tag' => 'Goods', 'NotifyUrl' => $NotifyUrl, 'openid' => session('openid'), );
		$jsParms = $this -> createWxOrder($conf);
		$this -> ajaxReturn(array('s' => true, 'm' => 'get OK', 'd' => $jsParms));

	}

	public function createWxOrder($conf) {
		Vendor('WxPay.WxPayApi');
		Vendor('WxPay.JsApiPay');
		$tools = new \JsApiPay();
		$input = new \WxPayUnifiedOrder();
		$input -> SetBody($conf['body']);
		$input -> SetAttach($conf['attach']);
		$input -> SetOut_trade_no($conf['out_trade_no']);
		$input -> SetTotal_fee($conf['total_fee']);
		$input -> SetTime_start(date("YmdHis"));
		$input -> SetTime_expire(date("YmdHis", time() + 600));
		$input -> SetGoods_tag($conf['goods_tag']);
		$input -> SetNotify_url($conf['NotifyUrl']);
		$input -> SetTrade_type("JSAPI");
		$input -> SetOpenid($conf['openid']);
		$order = \WxPayApi::unifiedOrder($input);
		$jsApiParameters = $tools -> GetJsApiParameters($order);
		//获取共享收货地址js函数参数
		//$editAddress = $tools->GetEditAddressParameters();
		return $jsApiParameters;
	}

	function lg() {
		$callback = 'http://zhijin.lxrbk.com/index.php/Home/Wx/lgback';
		$url = $this -> WX -> getOauthRedirect($callback);
		header('location:' . $url);
	}

	function lgback() {
		$tk = $this -> WX -> getOauthAccessToken();
		session('openid', $tk['openid']);
		//$this->redirect('Wx/pay/');
		header('location:/index.php/Home/Wx/pay/?id=2');
	}

}
